package com.billsharing.server;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class BillReport
 */
@WebServlet("/BillReport")
public class BillReport extends HttpServlet {
	private static final long serialVersionUID = 1L;
	int uid, i=0;

	double billamt1;
    String result;
    Connection conn;
    int count=0;
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		PrintWriter out=response.getWriter();
		String billamt,billdesc,billdate,paidemail,sharedemail;
		uid = Integer.parseInt(request.getParameter("uid"));
		billamt=request.getParameter("billamt");
		double credit = 0,debit = 0;
		billdesc=request.getParameter("billdesc");
		billdate=request.getParameter("billdate");
		paidemail = request.getParameter("paidid");
		sharedemail=request.getParameter("sharedids");
		String credit1 = "0",debit1 = "0";
		billamt1=Double.parseDouble(billamt);
		boolean result1 = false;
		try
		{
		 Class.forName ("com.mysql.jdbc.Driver").newInstance();
         conn = DriverManager.getConnection ("jdbc:mysql://csdb.csc.villanova.edu/auppalap", "auppalap", "fL00355727");
         System.out.println ("Database connection established");
         Bill b= new Bill();
         result=b.GrouporFriend(sharedemail);
         
         if(result=="fnd")
         {
        	 
        result1=b.reportBilltoFriend(billdesc,billamt1,paidemail,sharedemail);
        	
         }
         else if(result=="grp")
         {
        	 Group grp=new Group();
        	 int gid=grp.getGid(sharedemail);
        	 Statement s=conn.createStatement();
        	 s.executeQuery("select count(*) as count from GroupMembers where groupid="+gid);
        	 ResultSet rs=s.getResultSet();
        	 while(rs.next())
        	 {
        		 count=rs.getInt("count");
        	 }
        	 
        	 result1=b.reportBilltoGroup(billdesc, billamt1, paidemail, gid,count);
         }
         else
         {
         }
        
         }
		catch(Exception e)
		{
			e.printStackTrace();
		}
		out.print(result1);    
	}

}
